<template>
  <div class="view-wrapper">
    <div class="listBox">
      <div class="top-steps">
        <el-steps :active="stepNum" align-center>
          <el-step title="设置卡信息"></el-step>
          <el-step title="设置商家与优惠"></el-step>
          <el-step title="导入会员"></el-step>
          <el-step title="成功"></el-step>
        </el-steps>
      </div>
      <div class="main">
        <div class="firstStep" v-if="stepNum == 1">
          <el-form
            :inline="true"
            :rules="rules"
            :model="firstForm"
            ref="firstForm"
            label-width="150px"
          >
            <el-form-item label="卡类型：">
              <div class="el-input">福利卡</div>
            </el-form-item>
            <el-form-item label="发卡主体：" >
              <div class="el-input">{{merchantName}}</div>
            </el-form-item>
            <el-form-item label="卡封面：" prop="individuationCardCover">
              <el-upload
                class="avatar-uploader"
                :action="action"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="firstForm.individuationCardCover"
                  :src="firstForm.individuationCardCover"
                  class="cover_img"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <span style="color: #1890ff">建议尺寸上传宽333px高149px的图片</span>
            </el-form-item>
            <el-form-item label="卡名称：" prop="name">
              <el-input v-model="firstForm.name" placeholder="请输入卡名称"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="卡有效期：" prop="validityType">
                  <el-select v-model="firstForm.validityType" placeholder="请选择">
                    <el-option
                      v-for="item in dataOptions"
                      :key="item.id"
                      :label="item.value"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="firstForm.validityType == 2">
                <el-form-item label="截止日期：" prop="validityEndTime">
                  <el-date-picker
                    v-model="firstForm.validityEndTime"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            
            
            <el-form-item label="卡金：" prop="worth">
              <el-input v-model="firstForm.worth" placeholder="请输入卡金">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="发行数量：" prop="issueTotal">
              <el-input v-model="firstForm.issueTotal" placeholder="请输入发行数量">
                <template slot="append">张</template>
              </el-input>
            </el-form-item>
            <el-form-item label="温馨提示：">
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="firstForm.assetIntroduce"
                show-word-limit
                :autosize="{ minRows: 4}"
              >
              </el-input>
            </el-form-item>
            <el-form-item class="bot_box">
              <el-button @click="handleBack">取消</el-button>
              <el-button type="primary" @click="firstSubmitForm('firstForm')">保存下一步</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="secondStep" v-if="stepNum == 2">
            <div class="selShop">
              <div class="lable">选择店铺：</div>
              <el-select v-model="shoptype" multiple :filterable="true" :clearable="true" @remove-tag="removeTag" placeholder="请选择">
                <el-option
                  v-for="item in shopList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-button style="margin-left: 10px" @click="handleGenerate" type="primary">生成商家优惠信息</el-button>
            </div>
            <div class="formBox">
              <el-form :model="secondForm" :rules="secondRules" ref="secondForm">
                <el-table
                  :data="secondForm.formData"
                  border
                  style="width: 100%">
                  <el-table-column fixed type="index" label="序号" width="60">
                  </el-table-column>
                  <el-table-column prop="merchantName" label="商家账号名称">
                    <template slot-scope="scope">
                      <div style="margin-bottom: 22px;">{{scope.row.merchantName}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="shopName" label="店铺名称">
                    <template slot-scope="scope">
                      <div style="margin-bottom: 22px;">{{scope.row.shopName}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="serviceFee" label="*平台服务费率（%）" width="130">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'formData.' + scope.$index + '.serviceFee'"
                        :rules="secondRules.serviceFee">
                        <el-input v-model="scope.row.serviceFee" placeholder="请输入" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="settlementType" label="*结算方式" width="160">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'formData.' + scope.$index + '.settlementType'"
                        :rules="secondRules.settlementType">
                        <el-select class="selectBox" v-model="scope.row.settlementType" placeholder="请选择">
                          <el-option
                            v-for="item in settlementTypeList"
                            :key="item.id"
                            :label="item.value"
                            :value="item.id"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="discount" label="*消费打折" width="250">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'formData.' + scope.$index + '.discountType'"
                        :rules="secondRules.discountType">
                        <el-radio-group v-model="scope.row.discountType">
                          <el-radio :label="2">无</el-radio>
                          <el-radio :label="1"><span>打</span>
                            <el-form-item 
                              :prop="'formData.' + scope.$index + '.discount'"
                              :rules="secondRules.discount" v-if="scope.row.discountType == 1" >
                              <el-input v-model="scope.row.discount" placeholder="">
                                <template slot="append">折</template>
                              </el-input>
                            </el-form-item>
                          </el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="date" label="其他活动">
                    <template slot-scope="scope">
                      <el-form-item>
                        <el-input type="textarea" v-model="scope.row.activityContent" placeholder="请输入"  :autosize="{ minRows: 2}"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    label="操作"
                    width="180">
                    <template slot-scope="scope">
                      <el-button @click="placedTop(scope.row.merchantId)" type="text" size="small">置顶</el-button>
                      <el-button @click="up(scope.row.merchantId)" type="text" size="small">升序</el-button>
                      <el-button @click="handledown(scope.row.merchantId)" type="text" size="small">降序</el-button>
                      <el-button @click="deleteMerchants(scope.row.merchantId)" type="text" size="small">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-form-item class="bot_box">
                  <el-button @click="handleprev()">上一步</el-button>
                  <el-button @click="handleSkip">跳过</el-button>
                  <el-button type="primary" @click="secondSubmitForm('secondForm')">保存下一步</el-button>
                </el-form-item>
              </el-form>
            </div>
        </div>
        <div class="thirdStep" v-if="stepNum == 3">
          <div class="title">
            <div class="left">计划发卡数量：{{firstForm.issueTotal}}张</div>
              <el-button type="text" @click="importTemplate">导入模版.xlsx</el-button>
          </div>
          <div class="formBox">
            <div class="btnBox">
                <el-upload
                  class="upload-demo"
                  :action="fileaction"
                  :headers="headers"
                  :data="fileData"
                  :limit="1"
                  :on-success="handleFileChange">
                  
                  <!-- :file-list="fileList" -->
                  <el-button type="primary">表格导入</el-button>
                  <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>
                <el-button type="warning" style="margin-left: 10px" @click="handAddMender">新增会员</el-button>
            </div>
            <ex-table
              ref="table"
              :table-column="tableColumn"
              :table-data="memberList"
              @pageSizeChange="handleSizeChange"
              @currentPageChange="handleCurrentChange"
            >
              <template v-slot:operate="{ scope }">
                <el-button size="small" @click="deleteMember(scope.row.phone)"
                  >删除</el-button
                >
              </template>
            </ex-table>
            <div class="bot_box">
              <el-button @click="handleprev">上一步</el-button>
              <el-button @click="handleThree">跳过</el-button>
              <el-button type="primary" @click="thirdSubmitForm()">保存下一步</el-button>
            </div>
          </div>
        </div>
        <div class="fourthStep" v-if="stepNum == 4">
          <div class="imgBox">
              <img src="@/static/sign.success.png" alt="" />
              <p >发卡成功</p>
          </div>
          <div class="bot_box">
            <el-button @click="handleBack">返回</el-button>
            <el-button type="primary" @click="lookDetail">查看卡详情</el-button>
          </div>
        </div>
      </div>
    </div>
    <add-member
      ref="childRef"
      v-if="detailDialog"
      :visible.sync="detailDialog"
      @success="_handleSuccess"
    />
  </div>
</template>
<script>
// components
import { allList, getDelete, deleteActivity,changeStatus } from "@/api/operateActive";
import {shopSelectDown,adminDict,addBridgeCard } from "@/api/bridgeCard"
import { getToken } from '@/utils/auth'
import addMember from './components/addMember'
// mixins
import handlePageMixin from "@/mixins/handlePageMixin";
export default {
  //   name: "",
  components: {
    addMember
  },
  mixins: [handlePageMixin],
  data() {
    var validateDiscount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入折扣'));
      } else {
        if (value< 0 || value >= 10) {
          callback(new Error('请输入0~10的数字'));
        }
        callback();
      }
    };
    return {
      detailDialog: false,
      stepNum: 1,
      action: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
      fileaction: process.env.VUE_APP_BASE_API + "/asset/card/weal/user/importData",
      dataOptions: [],//有效期类型
      shopList:[],// 店铺列表
      shoptype: [],//
      selShopList:[],
      settlementTypeList:[],//结算类型
      merchantName:'', 
      headers: {},//设置上传文件请求头
      memberList: [],
      fileData: {
        assetId: ''
      },
      assetId: '',
      firstForm:{//第一步提交的数据
        cardType: 7,//团体福利卡
        merchantId: '',//行业协会Id
        name: '',//名称
        individuationCardCover: '',//个性化封面
        validityType: '',//有效期类型 1 长期有效 2 限制日期 asset_card_validity_type 
        validityStartTime: '',//有效期开始时间 (有效期类型 为 2 限制日期时必填)
        validityEndTime: '',//有效期截止时间(有效期类型 为 2 限制日期时必填)
        worth: '',//卡金
        issueTotal: '',//发行数量
        assetIntroduce: '',//卡介绍说明
      },
      rules: {
        individuationCardCover: [{ required: true, message: "请上传照片", trigger: "blur" }],
        name: [{ required: true, message: "请输入卡名称", trigger: "blur" }],
        validityType: [{ required: true, message: "请选择卡有效期类型", trigger: "change" }],
        worth: [{ required: true, message: "请输入卡金", trigger: "blur" }],
        issueTotal: [
          { required: true, message: "请输入发行数量", trigger: "blur" },
        ],
        validityEndTime: [{ required: true, message: "请选择截止日期", trigger: "change" }],
      },
      discountType:[
        {id:0,value: '无'},
         {id:0,value: '大'},
      ],
      secondForm: {//第二步提交数据
        formData: [],
      },
      secondRules: {
        serviceFee: [{ required: true, message: '请输入', trigger: 'blur' }],
        settlementType:[ { required: true, message: "请选择", trigger: "change" },],
        discount: [{ required: true, message: '请输入', trigger: 'blur' }],
        discountType: [{ required: true, message: '请选择', trigger: 'blur' }],
        
        discount:[ { validator: validateDiscount, trigger: "blur" },]
      },
      tableColumn: [
        { prop: "phone", label: "*会员手机号" },
        { prop: "name", label: "*会员名字", width: "200" },
        {
          label: "操作",
          slot: true,
          slotName: "operate",
          width: "250",
          fixed: "right",
        },
      ],
    };
  },
  created() {
    console.log('getToken()',getToken())
    this.headers ={'X-Access-Token' : getToken() || ''}
    this.firstForm.merchantId = this.$route.query.id
    this.merchantName = this.$route.query.shopName
    this.getShopDict()
    this.getlinkagelist()
  },
  computed: {},
  methods: {
    getlinkagelist() {
      //获取有效期字典
      const params = {
        dictType: "asset_card_validity_type,asset_card_weal_settlement_type ",
      };
      adminDict(params).then((res) => {
        this.dataOptions = res.result[0].dictList;
        this.settlementTypeList = res.result[1].dictList;
        var obj = {
          additionalValue: '',
          id: '2',
          value: '限制时间',
        }
        this.dataOptions.splice(1,0,obj)
      });
    },
    //获取下拉店铺
    getShopDict(){
      shopSelectDown('').then((res) => {
        console.log('res',res)
        if(res.code == 200){
          this.shopList = res.result
        }
      });
    },
    //卡封面
    handleAvatarSuccess(res, file) {
      this.firstForm.individuationCardCover = res.result.url;
    },
    //上传照片前
    beforeAvatarUpload(file) {
      console.log(file);
      const format = ["image/jpeg", "image/jpg", "image/png"];
      const isJPG = format.some((item) => file.type === item);
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpeg,jpg,png格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isJPG && isLt2M;
    },
    //生成商家优惠信息
    handleGenerate(){
      this.selShopList = []
      console.log('this.shoptype',this.shopList)
      this.shoptype.forEach(aitem =>{
        this.shopList.forEach(bitem =>{
          if(aitem == bitem.id){
            var obj = {
              merchantId: '',
              merchantName: '',
              shopId: '',
              shopName: '',
              serviceFee: 5,
              settlementType: '1',
              discount: '',
              discountType: 2,//是否打折 1打折 2不打折  
              activityContent: '',
            }
            var additionalValue = JSON.parse(bitem.additionalValue)
            obj.merchantId = bitem.id
            obj.shopId = additionalValue.shopId
            obj.merchantName = additionalValue.merchantName
            obj.shopName = bitem.value
            this.selShopList.push(obj)
          }
        })
        
        
      })
      
      this.secondForm.formData = this.selShopList
    },
    //导入文件
    handleFileChange(res, file) {
      console.log('文件',res)
      if(res.code == 200){
        this.memberList = this.memberList.concat(res.result) 
      }else{
        this.$message.error(res.message);
      }

      
      // this.firstForm.individuationCardCover = res.result.url;
    },
    // 上一步
    handleprev(){
      if(this.stepNum != 0 ){
        this.stepNum --
      }
    },
    //跳过
    handleSkip(){
      this.stepNum++
    },
    handleThree(){
      this.addCardForm()
    },
    //返回
    handleBack(){
      this.$router.go(-1)
    },
    
    //第一步 ===》 下一步
    firstSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.stepNum ++
        } else {
          
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //第二步提交
    secondSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.stepNum ++
          console.log("secondForm",this.secondForm)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //第三步提交
    thirdSubmitForm() {
      if(this.memberList.length==0){
        this.$message.error("请导入会员列表或者新增会员");
      }else{
        this.addCardForm()
      }
      
    },
    addCardForm(){
      let Base64 = require("js-base64").Base64;
      var assetIntroduce = this.firstForm.assetIntroduce
      assetIntroduce = Base64.encode(assetIntroduce);
      var data = {
        buyMoney: this.firstForm.worth,
        giveMoney: 0,
        shopStatus: 1,
        discount: '',
        refundRule: '1111',
        ...this.firstForm,
        assetCardWealVOList:this.secondForm.formData,
        assetCardWealUserVOList: this.memberList
      }
      data.assetIntroduce = assetIntroduce
      addBridgeCard(data).then(res => {
        const {code,message} = res
        var type = ''
        if(code == 200){
          type = 'success'
          this.stepNum = 4
          this.assetId = res.result.assetId
        }else{
          type = 'error'
        }
        this.$message({
          message: message,
          type: type,
          duration: 1500,
        })
      }).finally(() => {
        this.loading = false
      })
    },
    //第四步提交
    fourthSubmitForm(){},

    //查看详情
    lookDetail(){
      this.$router.push({
        path: "/merchants/bridge-card-detail",
        query:{
          assetId: this.assetId
        }
      })
    },
    //删除会员
    deleteMember(phone){
      this.memberList.forEach((item,index) =>{
        if(item.phone == phone){
          console.log('index',index)
          this.memberList.splice(index,1)
        }
      })
    },
    //置顶
    placedTop(id){
      var num = 0
      this.secondForm.formData.map((item,index)=>{
        // console.log(this.secondForm.formData.splice(index , 1)[0])
        if(item.merchantId == id){
           num = index
          console.log('index',index)
          this.secondForm.formData.unshift(this.secondForm.formData.splice(num , 1)[0]);
        }
        
      })
    },
    //升序
    up(id){
      var num = 0
      this.secondForm.formData.forEach((item,index) =>{
        if(item.merchantId == id){
          num = index
        }
      })
      console.log('num',num)
      if(num != 0){
        this.secondForm.formData[num] = this.secondForm.formData.splice(num - 1,1,this.secondForm.formData[num])[0];
      }else{
        this.$message.warning("已是最顶一个了");
      }
    },
    //降序
    handledown(id){
      var num = 0
      this.secondForm.formData.forEach((item,index) =>{
        if(item.merchantId == id){
          num = index
        }
      })
      console.log(num)

      if(num != this.secondForm.formData.length-1){
        this.secondForm.formData[num] = this.secondForm.formData.splice(num+1,1,this.secondForm.formData[num])[0];
      }else{
        this.$message.warning("已是最低一个了");
      }
    },
    //删除商家
    deleteMerchants(id){
      this.secondForm.formData.forEach((item,index) =>{
        if(item.merchantId == id){
          this.secondForm.formData.splice(index,1)
          
        }
      })
      this.shoptype.forEach((item,index) =>{
        if(item == id){
          this.shoptype.splice(index,1)
          
        }
      })
    },
    removeTag(){
      console.log(this.shoptype)
      this.handleGenerate()
    },
    //导入模板
    importTemplate(){
      location.href = 'https://www.milianmeng.net/group1/M00/00/3A/rBAAB2Hg5emAUtvsAAAisHvBBo053.xlsx'
    },
    //新增会员成功后回调
    _handleSuccess(data) {
      console.log("data", data);
      console.log(" this.memberList",  this.memberList);
      this.memberList.push(data)
    },
    //新增会员
    handAddMender(){
      this.detailDialog = true
    }
  },
};
</script>
<style lang="scss" scoped>
.listBox {
  box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
  background-color: #fff;
  border-radius: 8px;
  //   height: 120px;
  padding: 20px 20px;
  margin-top: 10px;
}
.top-steps{
  margin-bottom: 40px;
}
.el-form--inline .el-form-item{
  display: block;
}
.bot_box{
  display: flex !important;
  justify-content: center;
}
.cover_img {
  width: 208px;
  height: 128px;
}
.avatar-uploader {
    border: 1px dashed #d9d9d9;
    width: 208px !important;
    height: 128px !important;
  }
  .avatar-uploader .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 208px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .firstStep{
    .el-input{
      width: 250px;
    }
    .el-textarea {
      width: 600px;
    }
  }
  //第二步样式
  .secondStep{
      .selShop{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .lable{
          color: #606266;
        } 
        .el-select{
          width: 500px;
        }
      }
      .formBox{
        margin: 40px 0 40px 0;
        .cell{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .el-input{
          width: 120px;
        }
        .selectBox{
          .el-input{
            width: 120px;
          }
        }
        .el-radio{
          display: flex;
          justify-content: flex-start;
          align-items: center;
        }
        .el-radio-group{
          display: flex;
        }
        ::v-deep .el-radio__label{
          display: flex;
          justify-content: flex-start;
          align-items: center;
        }
        .bot_box{
          margin-top: 40px;
        }
      }
  }
  // 第三部样式
  .thirdStep{
    .title{
      display: flex;
      align-items: center;
      justify-content: flex-start;
      .left{
        font-size: 20px;
        font-weight: 500;
      }
    }
    .formBox{
      margin-top: 10px;
      .btnBox{
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        margin-bottom: 20px;
      }
    }
  }
  .fourthStep{
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    .imgBox{
      margin-top: 100px;
      margin-bottom: 100px;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      img{
        width: 100px;
        height: 100px;
      }
      p{
        font-size: 24px;
        color: #333;
        font-weight: 600;
        margin-top: 30px;
      }
    }
  }
</style>
